# -*- coding:utf-8 -*- #
from threading import RLock
import shutil
import copy
import marshal


#引入上层目录模块方法
import sys
sys.path.append("..")

from conf.configure import alarm_backup_path

lock = RLock()
tmp = alarm_backup_path + '.tmp'

def writealarminfo(obj):
    """objs: dictionary objects
    将字典存入文件中
    """

    # obj = {201: [2, 1333679619, [10, 10, 10, 10]]}
    obj = copy.deepcopy(obj)
    print obj
    
    lock.acquire()
    try:
        f = open(tmp, 'w')
        # 把这些数据序列化到文件中,文件必须以二进制模式打开
        marshal.dump(obj, f)
        f.close()
        shutil.copy2(tmp, alarm_backup_path)
    except IOError:
        pass
    lock.release()


def readalarminfo():
    '''从二进制文件中读取预警信息
    文件 /root/pymonitor/probe/log/alarm_backup.tmp
    '''
    d = {}
    lock.acquire()
    try:
        f = open(tmp, 'r')
        # 从文件中读取序列化的数据
        d = marshal.load(f)
    except IOError:
        pass
    except ValueError:
        f = open(alarm_backup_path, 'r')
        # 从文件中读取序列化的数据
        d = marshal.load(f)
    lock.release()
    return d
